import axios from 'axios'

import store from '@/store'

// 配置基地址
const service = axios.create({
  baseURL: 'http://hmmm-api.itheima.net', // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 5000 // request timeout
})

// 请求拦截器
service.interceptors.request.use(
  config => {
    const { token } = store.state.user
    if (token) {
      config.headers.Authorization = `Bearer ${token}`
    }
    return config
  },
  error => {
    console.log(error) // for debug
    return Promise.reject(error)
  }
)
// 响应拦截器
service.interceptors.request.use((config) => {
  const token = store.state.user.token
  if (token) config.headers.Authorization = `Bearer ${token}`
  return config
}, (error) => {
  return Promise.reject(error)
}
)

service.interceptors.response.use((res) => {
  const { data } = res
  return data
}, (error) => {
  return Promise.reject(error)
})

export default service
